package ltd.dujiabao.reserver.util;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.EnglishOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.EnglishOCRResponse;

/**
 * @author : DuJiabao
 * @Project : reserver
 * @Time : 2021/11/6 0:35
 * @Desc :
 */
public class OcrClientUtils {
    /**
     * 构造一个腾讯云ocr的客户端
     *
     * @param secretId    密钥id
     * @param secretKey   密钥
     * @param ocrEndpoint 节点，按默认的就好
     * @param regionName  区域名
     * @return
     */
    public static OcrClient buildClient(String secretId, String secretKey, String ocrEndpoint, String regionName) {
        Credential cred = new Credential(secretId, secretKey);
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(ocrEndpoint);
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        return new OcrClient(cred, regionName, clientProfile);
    }

    /**
     * 执行ocr操作
     *
     * @param url         图片的url
     * @param secretId    密钥id
     * @param secretKey   密钥
     * @param ocrEndpoint 节点，按默认的就好
     * @param regionName  区域名
     * @return 识别结果
     */
    public static String doOcr(String url, String secretId, String secretKey, String ocrEndpoint, String regionName) {
        OcrClient ocrClient = buildClient(secretId, secretKey, ocrEndpoint, regionName);
        EnglishOCRRequest req = new EnglishOCRRequest();
        req.setImageUrl(url);
        try {
            EnglishOCRResponse resp = ocrClient.EnglishOCR(req);
            if (resp != null && resp.getTextDetections() != null && resp.getTextDetections().length > 0) {
                return resp.getTextDetections()[0].getDetectedText();
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return null;
    }
}
